package com.demo.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.demo.common.BaseController;
import com.demo.interceptor.UserInterceptor;
import com.demo.po.Address;
import com.demo.po.MapAttr;
import com.demo.po.User;
import com.demo.util.HtmlUtil;
import com.demo.vo.Addr;
import com.demo.vo.Pic;
import com.jfinal.aop.Before;
import com.jfinal.upload.UploadFile;

/**
 * UserController
 * 所有 sql 写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
@Before(UserInterceptor.class)
public class UserController extends BaseController {
	
	
	public void index() {
		setAttr("userPage", new User().findUser());
		renderVelocity("user.vm");
	}
	
	public void save() {
		getModel(User.class).save();
		redirect("/user");
	}
	
	public void add(){
		render("add.html");
	}
	
	public void delete() {
		User.dao.deleteById(getParaToInt());
		redirect("/user");
	}
	
	
	public void showMapDialog(){
		String username = getSessionAttr("username");
		
		setAttr("username", username);
		
		MapAttr mapAttr = new MapAttr();
		List<MapAttr> mapAttrs = mapAttr.find("select * from mapattr where username=?", username);
		List<Pic> pics = new ArrayList<Pic>();
		for(MapAttr m:mapAttrs){
			Pic pic = new Pic();
			pic.setName(m.getStr("addname"));
			pic.setPicadd(m.getStr("picadd"));
			pic.setPosL(m.getStr("posL"));
			pic.setPosR(m.getStr("posR"));
			pics.add(pic);
		}
		setAttr("pics", pics);
		
		//设置双方地址
		Address address = new Address();
		List<Address> sourceAdd = address.find("select * from address where userid=? and addtype=?", this.getUserId(username),"1");
		Addr a1 = new Addr();
		if(sourceAdd != null && sourceAdd.size() > 0){
			a1.setName((String)sourceAdd.get(0).get("name"));
			a1.setLeft((String)sourceAdd.get(0).get("posL"));
			a1.setRight((String)sourceAdd.get(0).get("posR"));
			setAttr("towardpoint", a1);
		}
		
		List<Address> sourceAdd2 = address.find("select * from address where userid=? and addtype=?", this.getUserId(username),"0");
		Addr a2 = new Addr();
		if(sourceAdd2 != null && sourceAdd2.size() > 0){
			a2.setName((String)sourceAdd2.get(0).get("name"));
			a2.setLeft((String)sourceAdd2.get(0).get("posL"));
			a2.setRight((String)sourceAdd2.get(0).get("posR"));
			setAttr("sourcepoint", a2);
		}
		

		renderVelocity("/mapdisplay/index.vm");
	}
	
	public void createHtml(){
		String username = getSessionAttr("username");
		String path = getRequest().getRequestURL().toString().replace("createHtml", "showMapDialog");
		String url = path;
		
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet;
		HttpResponse httpResponse;
		HttpEntity httpEntity;
		
		
		String html = HtmlUtil.getContent(url);
		
		String realPath = getRequest().getSession().getServletContext().getRealPath("/");
//		String realPath = getRequest().getContextPath();
		String writePath = realPath+"mapdisplay"+File.separator+username+".html";
		
	    File file = new File(writePath);
	    FileOutputStream fos;
		try {
			 fos = new FileOutputStream(file);
		     if(!file.exists()){
		          file.createNewFile();
		     }			 
		     byte[] byteArr = html.getBytes();
		     fos.write(byteArr);
		     fos.flush();
		     fos.close();			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String add = getRequest().getContextPath() +"mapdisplay/"+username+".html";
		renderHtml("访问地址："+"<a href='"+add+"'"+"></a>");
	}
	
	
	public void putParam(){
		renderVelocity("/mapdisplay/param.vm");
	}
	
	public void uploadparam(){
		String username = getSessionAttr("username");
		MapAttr m = new MapAttr();
		m.deleteByName(username);
		
		List<UploadFile> files = getFiles(username);
		for(int i = 1;i <= files.size();i++){
			UploadFile f = files.get(i-1);
			MapAttr mapAttr = new MapAttr();
			String imgname = f.getFileName();
			System.out.println(f.getSaveDirectory());
			String picadd = username+"/"+imgname;
			String postL = getPara("posL"+i);
			String postR = "";
			if(!StringUtils.isBlank(postL)){
				String[] postArr = postL.split(",");
				if(postArr.length > 1){
					postL = postArr[0];
					postR = postArr[1];
				}
			}
			
			String addname = getPara("addname"+i);
			
			mapAttr.set("addname", addname);
			mapAttr.set("picadd", picadd);
			mapAttr.set("posL", postL);
			mapAttr.set("posR", postR);
			mapAttr.set("username", username);
			mapAttr.set("pictype", "0");
			mapAttr.save();
		}
		
		String sourcepname = getPara("sourceposition");
		String towardname = getPara("towardposition");
		Address sAddress = new Address();
		Address tAddress = new Address();
		
		sAddress.deleteById(this.getUserId(username));
		
		sAddress.set("name", sourcepname);
		String sourceL = "113.30233";
		String sourceR = "23.233452";
		String source = getPara("sourceleft");
		if(!StringUtils.isBlank(source)){
			String[] postArr = source.split(",");
			if(postArr.length > 1){
				sourceL = postArr[0];
				sourceR = postArr[1];
			}
		}
		sAddress.set("posL", sourceL);
		sAddress.set("posR", sourceR);
		sAddress.set("userid", getUserId(username));
		sAddress.set("addtype", "1");
		sAddress.save();
		
		String targetL = "113.30233";
		String targetR = "23.233452";
		String target = getPara("towardleft");
		if(!StringUtils.isBlank(target)){
			String[] postArr = target.split(",");
			if(postArr.length > 1){
				targetL = postArr[0];
				targetR = postArr[1];
			}
		}
		tAddress.set("name", towardname);
		tAddress.set("posL",targetL);
		tAddress.set("posR", targetR);
		tAddress.set("userid", getUserId(username));
		tAddress.set("addtype", "0");
		tAddress.save();
		
		redirect("/user/showMapDialog");
		
	}

	
	
}


